<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      img {
        width: 400px;
        height: 300px;
      }
    </style>
  </head>
  <body>
    <div>
      <p></p>
      <img src="./img/img1.gif" alt="" />
    </div>
    <script>
      const imgs = ["./img/img2.gif", "./img/img3.gif", "./img/img4.gif", "./img/img5.png"];
      const img = document.querySelector("img");
      const test = document.querySelector("p");
      //  实现点击图片，切换下一张图片
      let index = 0;
 
      test.innerHTML = "我是第" + (index + 1) + "张图片";
      img.addEventListener("click", function () {
        if (index < imgs.length) {
          img.src = imgs[index];
          index++;
          test.innerHTML = "我是第" + (index + 1) + "张图片";
        }else{
          alert('没有了')
        }
 
        //  切换图片后，同时让浏览器提前加载下载一张图片
        if (index < imgs.length) {
          preLoad(imgs[index]);
        }
      });
 
      // 调用加载函数，页面一开始就加载数组第一个元素
      preLoad(imgs[0]);
      // 封装函数，新建一个img标签，然后增加src属性，让浏览器加载下一张图片
      function preLoad(src) {
        img.addEventListener("load", () => {
          // 创建一个新的img标签
          const img = document.createElement("img");
          // 给img添加src属性，为我们传进来的src
          img.src = src;
        });
      }
    </script>
  </body>
</html>